﻿using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace FCT551.Helper
{
    /// <summary>
    /// MES服务客户端，用于与MES系统进行数据交互
    /// </summary>
    public class MESServiceClient
    {
        private readonly string _baseUrl;
        private readonly HttpClient _httpClient;

        public MESServiceClient(string baseUrl = "http://192.168.100.47:5010")
        {
            _baseUrl = baseUrl;
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }

        #region 数据模型定义

        public class LoginRequest
        {
            [JsonProperty("EmpNo")]
            public string EmpNo { get; set; }

            [JsonProperty("EmpPw")]
            public string EmpPw { get; set; }
        }

        public class StageRequest
        {
            [JsonProperty("Stage")]
            public string Stage { get; set; }
        }

        public class SNPassRequest
        {
            [JsonProperty("WorkOrder")]
            public string WorkOrder { get; set; }

            [JsonProperty("SN")]
            public string SN { get; set; }

            [JsonProperty("Terminal")]
            public string Terminal { get; set; }

            [JsonProperty("TestResult")]
            public string TestResult { get; set; }

            [JsonProperty("EmpNo")]
            public string EmpNo { get; set; }
        }

        public class SNRequest
        {
            [JsonProperty("WorkOrder")]
            public string WorkOrder { get; set; }

            [JsonProperty("SN")]
            public string SN { get; set; }

            [JsonProperty("Terminal")]
            public string Terminal { get; set; }

            [JsonProperty("EmpNo")]
            public string EmpNo { get; set; }
        }

        public class BaseResponse
        {
            [JsonProperty("Result")]
            public string Result { get; set; }

            [JsonProperty("MSG")]
            public string Message { get; set; }

            public bool IsSuccess => Result == "OK";
        }

        public class TerminalInfo
        {
            [JsonProperty("PdlineCode")]
            public string ProductionLineCode { get; set; }

            [JsonProperty("Terminals")]
            public List<string> Terminals { get; set; }

            [JsonProperty("WorkOrders")]
            public List<WorkOrderDto> WorkOrders { get; set; }
        }

        public class WorkOrderDto
        {
            [JsonProperty("WorkOrder")]
            public string WorkOrder { get; set; }

            [JsonProperty("PartNo")]
            public string PartNumber { get; set; }

            [JsonProperty("PartName")]
            public string PartName { get; set; }
        }

        public class TerminalListResponse : BaseResponse
        {
            [JsonProperty("Data")]
            public List<TerminalInfo> Data { get; set; }
        }

        public class WorkOrderOutputResponse : BaseResponse
        {
            [JsonProperty("Data")]
            public WorkOrderOutputDto Data { get; set; }
        }

        public class WorkOrderOutputDto
        {
            [JsonProperty("WorkOrder")]
            public string WorkOrder { get; set; }

            [JsonProperty("CurrentProcess")]
            public string CurrentProcess { get; set; }

            [JsonProperty("OutputQty")]
            public decimal OutputQuantity { get; set; }
        }

        #endregion 数据模型定义

        #region 私有方法

        /// <summary>
        /// 发送POST请求到MES接口
        /// </summary>
        private async Task<T> PostAsync<T>(string endpoint, object data)
        {
            try
            {
                string json = JsonConvert.SerializeObject(data);
                MyLog.Info("Mes上传数据Json格式：" + json);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await _httpClient.PostAsync($"{_baseUrl}{endpoint}", content);
                response.EnsureSuccessStatusCode();

                string responseContent = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(responseContent);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"调用MES接口失败: {endpoint}", ex);
            }
        }

        #endregion 私有方法

        #region 公共接口方法

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="empNo">员工编号</param>
        /// <param name="empPw">密码</param>
        /// <returns>登录结果</returns>
        public async Task<BaseResponse> LoginAsync(string empNo, string empPw)
        {
            var request = new LoginRequest
            {
                EmpNo = empNo,
                EmpPw = empPw
            };

            return await PostAsync<BaseResponse>("/FCTData/Login", request);
        }

        /// <summary>
        /// 获取工作站列表
        /// </summary>
        /// <param name="stage">区段(SMT或DIPtoPACKING)，默认为DIPtoPACKING</param>
        /// <returns>工作站列表响应</returns>
        public async Task<TerminalListResponse> GetTerminalListAsync(string stage = "DIPtoPACKING")
        {
            var request = new StageRequest
            {
                Stage = stage
            };

            return await PostAsync<TerminalListResponse>("/FCTData/GetTerminalList", request);
        }

        /// <summary>
        /// 检查SN状态
        /// </summary>
        /// <param name="workOrder">工单</param>
        /// <param name="sn">序列号</param>
        /// <param name="terminal">工作站名称</param>
        /// <param name="empNo">员工编号</param>
        /// <returns>检查结果</returns>
        public async Task<BaseResponse> CheckRouteAsync(string workOrder, string sn, string terminal, string empNo)
        {
            var request = new SNRequest
            {
                WorkOrder = workOrder,
                SN = sn,
                Terminal = terminal,
                EmpNo = empNo
            };

            return await PostAsync<BaseResponse>("/FCTData/CheckRoute", request);
        }

        /// <summary>
        /// 过站接口
        /// </summary>
        /// <param name="workOrder">工单</param>
        /// <param name="sn">序列号</param>
        /// <param name="terminal">工作站名称</param>
        /// <param name="testResult">测试结果(PASS或FAIL)</param>
        /// <param name="empNo">员工编号</param>
        /// <returns>过站结果</returns>
        public async Task<BaseResponse> PassTerminalAsync(string workOrder, string sn, string terminal, string testResult, string empNo = "001")
        {
            var request = new SNPassRequest
            {
                WorkOrder = workOrder,
                SN = sn,
                Terminal = terminal,
                TestResult = testResult,
                EmpNo = empNo
            };

            return await PostAsync<BaseResponse>("/FCTData/PassTerminal", request);
        }

        /// <summary>
        /// 获取工单制程产出量
        /// </summary>
        /// <param name="workOrder">工单</param>
        /// <param name="terminal">工作站名称</param>
        /// <returns>工单产出量信息</returns>
        public async Task<WorkOrderOutputResponse> GetWorkOrderOutputQtyAsync(string workOrder, string terminal)
        {
            var request = new SNPassRequest
            {
                WorkOrder = workOrder,
                Terminal = terminal
            };

            return await PostAsync<WorkOrderOutputResponse>("/FCTData/GetWorkOrderOutputQty", request);
        }

        #endregion 公共接口方法
    }
}